package com.jackie.easyble.ui.activities.search

import android.bluetooth.le.ScanResult
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.jackie.easyble.IntentConstants
import com.jackie.easyble.R
import com.jackie.easyble.databinding.ActivityMultiDeviceScanBinding
import com.jackie.easyble.toastL
import com.jackie.easyble.ui.activities.connect.multi.MultipleDeviceConnectActivity
import com.jackie.easyble.ui.adapter.MultipleSelectScanResultRecyclerViewAdapter
import com.sscl.baselibrary.activity.BaseDataBindingAppCompatActivity
import com.sscl.baselibrary.utils.DebugUtil
import com.sscl.baselibrary.utils.DefaultItemDecoration
import com.sscl.easyble.BleManager
import com.sscl.easyble.extensions.getFailMsg
import com.sscl.easyble.extensions.indexOfScanResults
import com.sscl.easyble.interfaces.scans.OnBleScanListener

/**
 * 多设备扫描界面
 */
class MultiDeviceScanActivity : BaseDataBindingAppCompatActivity<ActivityMultiDeviceScanBinding>() {

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 属性声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /* * * * * * * * * * * * * * * * * * * 常量属性 * * * * * * * * * * * * * * * * * * */

    /**
     * 设备列表适配器
     */
    private val multipleSelectScanResultRecyclerViewAdapter =
        MultipleSelectScanResultRecyclerViewAdapter()

    /**
     * 下拉刷新回调
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        multipleSelectScanResultRecyclerViewAdapter.clear()
        if (BleManager.getScannerInstance().scanning) {
            BleManager.getScannerInstance().stopScan()
        }
        BleManager.getScannerInstance().startScan(true)
        binding.refreshLayout.isRefreshing = false
    }

    /**
     * 蓝牙设备搜索回调
     */
    private val onBleScanListener = object : OnBleScanListener {
        override fun onScanFindOneNewDevice(scanResult: ScanResult) {
            DebugUtil.warnOut(tag, "onScanFindOneNewDevice $scanResult")
            multipleSelectScanResultRecyclerViewAdapter.add(scanResult)
        }

        override fun onScanComplete() {
            DebugUtil.warnOut(tag, "onScanComplete")
        }

        override fun onBatchScanResults(results: List<ScanResult>) {
            DebugUtil.warnOut(tag, "onBatchScanResults ${results.size}")
        }

        override fun onScanFailed(errorCode: Int) {
            DebugUtil.warnOut(tag, "onScanFailed ${errorCode.getFailMsg()}")
        }

        override fun onScanResultInfoUpdate(result: ScanResult) {
            super.onScanResultInfoUpdate(result)
            DebugUtil.warnOut(tag, "onScanResultInfoUpdate $result")
            val indexOf =
                multipleSelectScanResultRecyclerViewAdapter.items.indexOfScanResults(result)
            if (indexOf < 0) return
            multipleSelectScanResultRecyclerViewAdapter[indexOf] = result
        }

        override fun onScanFindOneDevice(scanResult: ScanResult) {
            super.onScanFindOneDevice(scanResult)
            DebugUtil.warnOut(tag, "onScanFindOneDevice $scanResult")
        }
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 实现方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 设置布局
     */
    override fun setLayout(): Int {
        return R.layout.activity_multi_device_scan
    }

    /**
     * 标题栏的返回按钮被按下的时候回调此方法
     */
    override fun titleBackClicked(): Boolean {
        return false
    }

    /**
     * 在设置布局之前需要进行的操作
     */
    override fun doBeforeSetLayout() {

    }

    /**
     * 设置DataBinding
     * 可在此处设置binding的viewModel或观察者等操作
     */
    override fun setBinding() {
    }

    /**
     * 在设置布局之后，进行其他操作之前，所需要初始化的数据
     */
    override fun doBeforeInitOthers() {
        setTitleText(R.string.multi_search_device)
    }

    /**
     * 初始化控件数据
     */
    override fun initViewData(savedInstanceState: Bundle?) {
        binding.deviceListRv.layoutManager = LinearLayoutManager(this)
        binding.deviceListRv.addItemDecoration(DefaultItemDecoration.newLine(Color.GRAY))
        binding.deviceListRv.adapter = multipleSelectScanResultRecyclerViewAdapter
    }

    /**
     * 初始化其他数据
     */
    override fun initOtherData() {

    }

    /**
     * 初始化事件
     */
    override fun initEvents() {
        binding.refreshLayout.setOnRefreshListener(onRefreshListener)
        BleManager.getScannerInstance()
            .setOnBleScanListener(onBleScanListener)
    }

    /**
     * 在最后进行的操作
     */
    override fun doAfterAll() {
        binding.refreshLayout.autoRefresh()
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 重写方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.activity_multi_device_scan, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.next -> {
                doNext()
            }

            else -> {
                return false
            }
        }
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        BleManager.releaseBleScannerInstance()
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 执行下一步
     */
    private fun doNext() {
        val selectedScanResultList =
            multipleSelectScanResultRecyclerViewAdapter.getSelectedScanResultList()
        if (selectedScanResultList.isEmpty()) {
            toastL(R.string.select_none_device)
            return
        }
        if (BleManager.getScannerInstance().scanning) {
            BleManager.getScannerInstance().stopScan()
        }
        val intent = Intent(this, MultipleDeviceConnectActivity::class.java)
        intent.putExtra(IntentConstants.SCAN_RESULT_LIST, selectedScanResultList)
        startActivity(intent)
    }
}